package com.tanger.im;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.tanger.common.utils.JSON;
import org.apache.logging.log4j.util.Strings;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 本地磁盘IM记录同步
 * @Author Hchenbin
 * @Date 2024-01-02 08:56
 * @Version 1.0
 */
@Component
public class SyncIMDiskCacheHandle implements Job {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 每日凌晨0点整执行的定时任务:更新本地磁盘聊天记录
     */
    @Override
    public void execute(JobExecutionContext context) {
        //获取所有缓存key
        Set<String> keys = Optional.ofNullable(
                stringRedisTemplate.keys(String.format(CacheKey.IM_USER_INIT_RECORD,"*")))
                .orElseGet(Collections::emptySet);

        //获取value
        keys.parallelStream()
                .forEach(k -> {
                    //获取记录
                    List<IMMessagePush> mps = findValue(k);
                    String[] spkeys = k.split(":");
                    JsonNode node = IMUserRecordHelper.read(spkeys[3]);

                    //合并
                    List<IMMessagePush> _mps;
                    if (Objects.nonNull(node)) {
                        IMMessagePush[] pushes = JSON.parse(JSON.stringify(node), IMMessagePush[].class);
                        _mps = new ArrayList<>(pushes.length);
                        Collections.addAll(_mps, pushes);
                        _mps.addAll(mps);
                        _mps = _mps.stream()
                                .sorted(Comparator.comparing(IMMessagePush::getSendTime).reversed())
                                .collect(Collectors.toList());
                    } else {
                        _mps = new ArrayList<>();
                        _mps.addAll(mps);
                    }
                    IMUserRecordHelper.save(_mps, spkeys[3]);
                    stringRedisTemplate.delete(k);
                });
    }

    protected List<IMMessagePush> findValue(String key) {
        if (!Strings.isEmpty(key)) {
            String data = stringRedisTemplate.opsForValue().get(key);
            return JSONObject.parseArray(data,IMMessagePush.class);
        }
        return null;
    }
}
